package com.lyy.project.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyy.common.utils.*;
import com.lyy.common.utils.excel.ExcelUtils;
import com.lyy.common.utils.jxls.JxlsExport;
import com.lyy.project.pojo.ProProject;
import com.lyy.project.service.ProProjectService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 项目信息(ProProject)表控制层
 *
 * @author Yw
 * @since 2021-02-01 17:22:28
 */
@RestController
@RequestMapping("/proProject")
public class ProProjectController {
    /**
     * 服务对象
     */
    @Resource
    private ProProjectService proProjectService;

    /**
     * 创建项目信息
     * /proProject/createProProject
     * { "name":"项目名称",  "description":"描述",  "createDate":"创建时间",  "userId":"用户id",  "projectStatus":"项目状态，字典project_status",  "permission":"项目开发状态,0公开，1私有",  "details":"项目备注",  "updateDate":"修改时间",  "delFlag":"删除状态，0否 1是" }
     *
     * @param name          项目名称
     * @param description   描述
     * @param createDate    创建时间
     * @param userId        用户id
     * @param projectStatus 项目状态，字典project_status
     * @param permission    项目开发状态,0公开，1私有
     * @param details       项目备注
     * @param updateDate    修改时间
     * @param delFlag       删除状态，0否 1是
     * @return
     */
    @PostMapping("/createProProject")
    public Map<String, Object> createProProject(ProProject proProject) {
        AssertUtils.notNull(proProject.getName(), "项目名称不能为空");
        AssertUtils.notNull(proProject.getDescription(), "描述不能为空");
        AssertUtils.notNull(proProject.getCreateDate(), "创建时间不能为空");
        AssertUtils.notNull(proProject.getUserId(), "用户id不能为空");
        AssertUtils.notNull(proProject.getProjectStatus(), "项目状态，字典project_status不能为空");
        AssertUtils.notNull(proProject.getPermission(), "项目开发状态,0公开，1私有不能为空");
        AssertUtils.notNull(proProject.getDetails(), "项目备注不能为空");
        AssertUtils.notNull(proProject.getUpdateDate(), "修改时间不能为空");
        AssertUtils.notNull(proProject.getDelFlag(), "删除状态，0否 1是不能为空");
        proProjectService.createProProject(proProject);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键修改项目信息
     * /proProject/updateProProject
     * { "id":"项目id",  "name":"项目名称",  "description":"描述",  "createDate":"创建时间",  "userId":"用户id",  "projectStatus":"项目状态，字典project_status",  "permission":"项目开发状态,0公开，1私有",  "details":"项目备注",  "updateDate":"修改时间",  "delFlag":"删除状态，0否 1是" }
     *
     * @param id            项目id
     * @param name          项目名称
     * @param description   描述
     * @param createDate    创建时间
     * @param userId        用户id
     * @param projectStatus 项目状态，字典project_status
     * @param permission    项目开发状态,0公开，1私有
     * @param details       项目备注
     * @param updateDate    修改时间
     * @param delFlag       删除状态，0否 1是
     * @return
     */
    @PutMapping("/updateProProject")
    public Map<String, Object> updateProProject(ProProject proProject) {
        AssertUtils.notNull(proProject.getId(), "项目id不能为空");
        AssertUtils.notNull(proProject.getName(), "项目名称不能为空");
        AssertUtils.notNull(proProject.getDescription(), "描述不能为空");
        AssertUtils.notNull(proProject.getCreateDate(), "创建时间不能为空");
        AssertUtils.notNull(proProject.getUserId(), "用户id不能为空");
        AssertUtils.notNull(proProject.getProjectStatus(), "项目状态，字典project_status不能为空");
        AssertUtils.notNull(proProject.getPermission(), "项目开发状态,0公开，1私有不能为空");
        AssertUtils.notNull(proProject.getDetails(), "项目备注不能为空");
        AssertUtils.notNull(proProject.getUpdateDate(), "修改时间不能为空");
        AssertUtils.notNull(proProject.getDelFlag(), "删除状态，0否 1是不能为空");
        proProjectService.updateProProject(proProject);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 根据主键获取单个项目信息
     * /proProject/getProProject
     * { "id":"项目id" }
     *
     * @param id 项目id
     * @return
     */
    @GetMapping("/getProProject")
    public Map<String, Object> getProProject(ProProject proProject) {
        AssertUtils.notNull(proProject.getId(), "项目id不能为空");
        ProProject entity = proProjectService.getProProject(proProject);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("proProject", entity);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 根据主键删除项目信息
     * /proProject/deleteProProject
     * { "id":"项目id" }
     *
     * @param id 项目id
     * @return
     */
    @DeleteMapping("/deleteProProject")
    public Map<String, Object> deleteProProject(ProProject proProject) {
        AssertUtils.notNull(proProject.getId(), "项目id不能为空");
        proProjectService.deleteProProject(proProject);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * 查询项目信息列表
     * /proProject/selectProProjectList
     * { "id":"项目id",  "name":"项目名称",  "description":"描述",  "createDate":"创建时间",  "userId":"用户id",  "projectStatus":"项目状态，字典project_status",  "permission":"项目开发状态,0公开，1私有",  "details":"项目备注",  "updateDate":"修改时间",  "delFlag":"删除状态，0否 1是" }
     *
     * @param id            项目id
     * @param name          项目名称
     * @param description   描述
     * @param createDate    创建时间
     * @param userId        用户id
     * @param projectStatus 项目状态，字典project_status
     * @param permission    项目开发状态,0公开，1私有
     * @param details       项目备注
     * @param updateDate    修改时间
     * @param delFlag       删除状态，0否 1是
     * @return
     */
    @GetMapping("/selectProProjectList")
    public Map<String, Object> selectProProjectList(ProProject proProject) {
        List<ProProject> proProjects = proProjectService.selectProProjectList(proProject);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("proProjects", proProjects);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }

    /**
     * 查询项目信息列表
     * /proProject/selectProProjectCount
     * { "id":"项目id", "name":"项目名称", "description":"描述", "createDate":"创建时间", "userId":"用户id", "projectStatus":"项目状态，字典project_status", "permission":"项目开发状态,0公开，1私有", "details":"项目备注", "updateDate":"修改时间", "delFlag":"删除状态，0否 1是"}
     *
     * @param id            项目id
     * @param name          项目名称
     * @param description   描述
     * @param createDate    创建时间
     * @param userId        用户id
     * @param projectStatus 项目状态，字典project_status
     * @param permission    项目开发状态,0公开，1私有
     * @param details       项目备注
     * @param updateDate    修改时间
     * @param delFlag       删除状态，0否 1是
     * @return
     */
    @GetMapping("/selectProProjectCount")
    public Map<String, Object> selectProProjectCount(ProProject proProject) {
        int count = proProjectService.selectProProjectCount(proProject);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", count);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 查询项目信息列表分页
     * /proProject/selectProProjectPage
     * { "id":"项目id",  "name":"项目名称",  "description":"描述",  "createDate":"创建时间",  "userId":"用户id",  "projectStatus":"项目状态，字典project_status",  "permission":"项目开发状态,0公开，1私有",  "details":"项目备注",  "updateDate":"修改时间",  "delFlag":"删除状态，0否 1是" ,"pageNum":"页码","pageSize":"条数"}
     *
     * @param pageNum       页码
     * @param pageSize      页数
     * @param id            项目id
     * @param name          项目名称
     * @param description   描述
     * @param createDate    创建时间
     * @param userId        用户id
     * @param projectStatus 项目状态，字典project_status
     * @param permission    项目开发状态,0公开，1私有
     * @param details       项目备注
     * @param updateDate    修改时间
     * @param delFlag       删除状态，0否 1是
     * @return
     */
    @GetMapping("/selectProProjectPage")
    public Map<String, Object> selectProProjectPage(ProProject proProject, Integer pageNum, Integer pageSize) {
        AssertUtils.notNull(pageNum, "页码不能为空!");
        AssertUtils.notNull(pageSize, "条数不能为空!");
        PageHelper.startPage(pageNum, pageSize);
        List<ProProject> proProjects = proProjectService.selectProProjectList(proProject);
        PageInfo<ProProject> pageInfo = new PageInfo<>(proProjects);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageInfo", pageInfo);
        return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
    }


    /**
     * 导出项目信息
     * /proProject/exportProProjectExcel
     * { "id":"项目id",  "name":"项目名称",  "description":"描述",  "createDate":"创建时间",  "userId":"用户id",  "projectStatus":"项目状态，字典project_status",  "permission":"项目开发状态,0公开，1私有",  "details":"项目备注",  "updateDate":"修改时间",  "delFlag":"删除状态，0否 1是" }
     *
     * @param id            项目id
     * @param name          项目名称
     * @param description   描述
     * @param createDate    创建时间
     * @param userId        用户id
     * @param projectStatus 项目状态，字典project_status
     * @param permission    项目开发状态,0公开，1私有
     * @param details       项目备注
     * @param updateDate    修改时间
     * @param delFlag       删除状态，0否 1是
     * @return
     */
    @GetMapping("/exportProProjectExcel")
    public void exportProProjectExcel(HttpServletRequest request, HttpServletResponse response, ProProject proProject) {
        List<ProProject> proProjects = proProjectService.selectProProjectList(proProject);
        if (CommonUtils.isNotEmpty(proProjects)) {
            List<String> titles = new ArrayList<>();
            titles.add(" 序号 ");
            titles.add(" 项目名称 ");
            titles.add(" 描述 ");
            titles.add(" 创建时间 ");
            titles.add(" 用户id ");
            titles.add(" 项目状态，字典project_status ");
            titles.add(" 项目开发状态,0公开，1私有 ");
            titles.add(" 项目备注 ");
            titles.add(" 修改时间 ");
            titles.add(" 删除状态，0否 1是 ");
            List<List<String>> values = new ArrayList<>();
            int k = 0;
            for (ProProject entity : proProjects) {
                List<String> value = new ArrayList<>();
                value.add((++k) + "");
                value.add(entity.getName());
                value.add(entity.getDescription());
                value.add(DateUtils.formatDate(entity.getCreateDate()));
                value.add(entity.getUserId());
                value.add(entity.getProjectStatus());
                value.add(entity.getPermission());
                value.add(entity.getDetails());
                value.add(DateUtils.formatDate(entity.getUpdateDate()));
                value.add(entity.getDelFlag());
                values.add(value);
            }
            String address = Constants.address + "/wisdom/template/customTemplate.xls";
            String excelName = "项目信息.xls";
            Map<String, Object> beans = new HashMap<>();
            beans.put("titles", titles);
            beans.put("values", values);
            beans.put("date", DateUtils.formatDateTime(new Date()));
            JxlsExport.export(request, response, beans, excelName, address);
        }
    }

    /**
     * 根据主键逻辑删除项目信息
     * /proProject/deleteProProjectLogic
     * { "id":"项目id" }
     *
     * @param id 项目id
     * @return
     */
    @PutMapping("/deleteProProjectLogic")
    public Map<String, Object> deleteProProjectLogic(ProProject proProject) {
        proProject.setDelFlag("1");
        proProjectService.updateProProject(proProject);
        return ResultUtils.getResult(ResultInfo.SUCCESS);
    }

    /**
     * /proProject/importProProjectExcel  从excel表导入项目信息
     * 导入excel文件
     * {"file":"excel文件"}
     *
     * @param file excel文件
     */
    @PostMapping("/importProProjectExcel")
    public Map<String, Object> importProProjectExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        // 文件名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return ResultUtils.getResult(ResultInfo.UPLOAD_NOT_EXISTS);
        }
        try {
            InputStream inputStream = file.getInputStream();
            //创建工作簿
            Workbook wb = null;
            //判断表格格式
            if (fileName.toLowerCase().endsWith("xls")) {
                wb = new HSSFWorkbook(inputStream);
            } else if (fileName.toLowerCase().endsWith("xlsx")) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                return ResultUtils.getResult(ResultInfo.UPLOAD_TYPE_ERROR);
            }
            List<ProProject> proProjects = new ArrayList<>();
            List<Map<String, String>> resultMap = new ArrayList<>();
            Map<String, String> result = null;
            ProProject proProject = null;
            // 获取工作表的第一个Sheet
            Sheet hssfSheet = wb.getSheetAt(0);
            if (hssfSheet != null) {
                int index = -1;
                for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (ExcelUtils.getValue(hssfRow.getCell(0)).contains("项目名称") &&
                                ExcelUtils.getValue(hssfRow.getCell(1)).contains("描述") &&
                                ExcelUtils.getValue(hssfRow.getCell(2)).contains("创建时间") &&
                                ExcelUtils.getValue(hssfRow.getCell(3)).contains("用户id") &&
                                ExcelUtils.getValue(hssfRow.getCell(4)).contains("项目状态，字典project_status") &&
                                ExcelUtils.getValue(hssfRow.getCell(5)).contains("项目开发状态,0公开，1私有") &&
                                ExcelUtils.getValue(hssfRow.getCell(6)).contains("项目备注") &&
                                ExcelUtils.getValue(hssfRow.getCell(7)).contains("修改时间") &&
                                ExcelUtils.getValue(hssfRow.getCell(8)).contains("删除状态，0否 1是")) {
                            index = ++rowNum;
                            break;
                        }
                    }
                }

                if (index == -1) {
                    result = new HashMap<>();
                    result.put("reason", "excel模板不正确");
                    result.put("status", "1");
                    resultMap.add(result);
                    Map<String, Object> map = new HashMap<>();
                    map.put("resultMap", resultMap);
                    return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
                }

                // 循环行Row
                for (int rowNum = index; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow != null) {
                        if (StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(0))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(1))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(2))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(3))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(4))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(5))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(6))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(7))) &&
                                StringUtils.isBlank(ExcelUtils.getValue(hssfRow.getCell(8)))) {
                            continue;
                        }
                        proProject = new ProProject();
                        String name = ExcelUtils.getValue(hssfRow.getCell(0));//项目名称
                        if (StringUtils.isBlank(name)) {
                            result = new HashMap<>();
                            result.put("reason", "项目名称不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setName(name);
                        String description = ExcelUtils.getValue(hssfRow.getCell(1));//描述
                        if (StringUtils.isBlank(description)) {
                            result = new HashMap<>();
                            result.put("reason", "描述不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setDescription(description);
                        String createDate = ExcelUtils.getValue(hssfRow.getCell(2));//创建时间
                        if (StringUtils.isBlank(createDate)) {
                            result = new HashMap<>();
                            result.put("reason", "创建时间不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setCreateDate(DateUtils.formatDate(createDate));
                        String userId = ExcelUtils.getValue(hssfRow.getCell(3));//用户id
                        if (StringUtils.isBlank(userId)) {
                            result = new HashMap<>();
                            result.put("reason", "用户id不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setUserId(userId);
                        String projectStatus = ExcelUtils.getValue(hssfRow.getCell(4));//项目状态，字典project_status
                        if (StringUtils.isBlank(projectStatus)) {
                            result = new HashMap<>();
                            result.put("reason", "项目状态，字典project_status不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setProjectStatus(projectStatus);
                        String permission = ExcelUtils.getValue(hssfRow.getCell(5));//项目开发状态,0公开，1私有
                        if (StringUtils.isBlank(permission)) {
                            result = new HashMap<>();
                            result.put("reason", "项目开发状态,0公开，1私有不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setPermission(permission);
                        String details = ExcelUtils.getValue(hssfRow.getCell(6));//项目备注
                        if (StringUtils.isBlank(details)) {
                            result = new HashMap<>();
                            result.put("reason", "项目备注不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setDetails(details);
                        String updateDate = ExcelUtils.getValue(hssfRow.getCell(7));//修改时间
                        if (StringUtils.isBlank(updateDate)) {
                            result = new HashMap<>();
                            result.put("reason", "修改时间不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setUpdateDate(DateUtils.formatDate(updateDate));
                        String delFlag = ExcelUtils.getValue(hssfRow.getCell(8));//删除状态，0否 1是
                        if (StringUtils.isBlank(delFlag)) {
                            result = new HashMap<>();
                            result.put("reason", "删除状态，0否 1是不能为空！");
                            result.put("status", "1");
                            resultMap.add(result);
                            continue;
                        }
                        proProject.setDelFlag(delFlag);
                        proProjects.add(proProject);
                    }
                }
                if (CommonUtils.isNotEmpty(proProjects)) {
                    resultMap.addAll(proProjectService.importProProjectExcel(proProjects));
                }
            }
            inputStream.close();
            Map<String, Object> map = new HashMap<>();
            map.put("resultMap", resultMap);
            return ResultUtils.getResult(ResultInfo.SUCCESS, "", map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.getResult(ResultInfo.ERROR);
        }
        return ResultUtils.getResult(ResultInfo.FAILED);
    }
}